package com.aikon.wht.mongo;

import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 *
 */
@Component
public class MongodbPulish{


	@Autowired
	private MongoDBConfigService mongoDBConfigService;


	/**
	 * 插入.
	 *
	 * @param json
	 */
	public void insertJson(String json) {
		mongoDBConfigService.getCollection().insertOne(Document.parse(json));
	}

	/**
	 * 插入.
	 *
	 * @param map
	 */
	public void insertMap(Map<String, Object> map) {
		Document doc = new Document(map);
		mongoDBConfigService.getCollection().insertOne(doc);
	}

	/**
	 * 查询.
	 *
	 * @return FindIterable<Document>
	 */
	public FindIterable<Document> find() {
		return mongoDBConfigService.getCollection().find();
	}

	/**
	 * count.
	 *
	 * @param key
	 * @param value
	 * @return long
	 */
	public long count(String key, Object value) {
		Document doc = new Document();
		doc.put(key, value);
		return mongoDBConfigService.getCollection().count(doc);

	}

	/**
	 * 更新.
	 *
	 * @param oKey
	 * @param oValue
	 * @param nKey
	 * @param nValue
	 */
	public void updateMany(String oKey, Object oValue, String nKey, Object nValue) {
		UpdateOptions uo = new UpdateOptions();
		uo.upsert(true);// update or insert
		mongoDBConfigService.getCollection().updateMany(Filters.eq(oKey, oValue), new Document("$set", new Document(nKey, nValue)), uo);
	}

	/**
	 * 删除.
	 *
	 * @param oKey
	 * @param oValue
	 */
	public void deleteMany(String oKey, Object oValue) {
		mongoDBConfigService.getCollection().deleteMany(Filters.eq(oKey, oValue));
	}

	public void replace(String oKey, Object oValue, String nKey, Object nValue) {
		mongoDBConfigService.getCollection().replaceOne(Filters.or(Filters.eq(oKey, oValue)), new Document(nKey, nValue));
	}


}
